import conf
from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip

# 加载视频文件
video_path = "../input/0526_H.264.mp4"
video = VideoFileClip(video_path)

# 访问视频的持续时间（duration）属性
duration = video.duration
print("视频长度:", duration)

print ("支持的字幕字体：",TextClip.list("font") )

# 多行带时间范围的字幕字符串
subtitle_string = """
1
00:00:01,616 --> 00:00:03,166
sdsad春节在古代被赋予祛病消灾

2
00:00:04,233 --> 00:00:06,016
fdsf求吉祈福的功能

3
00:00:07,116 --> 00:00:7,666
dsadas很多古代饮食同样被赋予了祛病消疫的功能
"""

# 解析字幕字符串并创建TextClip实例
subtitle_clips = []
for line in subtitle_string.strip().split("\n\n"):
    num,time_range, text = line.split("\n")
    start_time, end_time = time_range.split(" --> ")
    start_time = start_time.replace(",", "")
    start_time = start_time.replace(":", "")
    start_time = int(start_time) / 1000

    end_time = end_time.replace(",", "")
    end_time = end_time.replace(":", "")
    end_time = int(end_time) / 1000

    text_duration = end_time - start_time

    # 字体决定是否能显示中文
    subtitle_clip = TextClip(text, font='FangSong', fontsize=80, color='white')
    subtitle_clip = subtitle_clip.set_start(start_time)
    subtitle_clip = subtitle_clip.set_end(end_time)
    subtitle_clip = subtitle_clip.set_duration(text_duration)
    subtitle_clip = subtitle_clip.set_position(("center", video.h-120))

    subtitle_clips.append(subtitle_clip)


# 将字幕叠加到视频上
clips=[video]+subtitle_clips
final_clip = CompositeVideoClip(clips,duration=duration)

# 生成带有字幕的视频文件
output_video_path = "output/output_video_with_subtitles.mp4"
final_clip.write_videofile(output_video_path, codec='libx264')